window.mq = {}

class window.mq.Defer
  constructor : () ->
    @pending = []
    @resolved = false
    @data = null

  then : (fn) ->
    d = new window.mq.Defer()
    d.resolve(fn(@data)) if @resolved
    @pending.push [fn, d] if not @resolved
    return d

  resolve : (data) ->
    @data = data
    @resolved = true

    for dd in @pending
      dd[1].resolve(dd[0](data))


window.mq.all = (arr) ->
  resolved = 0
  toresolve = arr.length
  
  defer = new window.mq.Defer()
  data = []

  for defered in arr
    defered.then (d) ->
      data.push d
      resolved += 1

      defer.resolve(data) if resolved == toresolve

  return defer

window.mq.stream = (arr) ->
  defer = new window.mq.Defer()
  for defered in arr
    defered.then (d) ->
      defer.resolve d
  return defer

